package com.mt.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.crypto.digest.Digester;
import com.mt.enums.RoleType;
import com.mt.enums.Status;
import com.mt.exception.GlobalException;
import com.mt.mapper.AdminMapper;
import com.mt.mapper.UserMapper;
import com.mt.pojo.AdminUser;
import com.mt.service.AdminService;
import com.mt.utils.IdUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author Wang
 * @Description
 * @date 2021/2/25-17:35
 */

@Service
public class AdminServiceImpl implements AdminService {
    @Resource
    AdminMapper adminMapper;
    @Resource
    UserMapper userMapper;

    @Override
    public AdminUser getAdminCinemaId(String userId) {
        return adminMapper.getAdminCinemaId(userId);
    }

    @Override
    public AdminUser addAdminUser(AdminUser admin) {

        admin.setUserId(IdUtils.getPrimaryKey());
        //密码加密
        String pw = "123456";
        Digester digester = DigestUtil.digester("sm3");
        String digesterPw = digester.digestHex(pw);
        admin.setPassword(digesterPw);
        boolean add = adminMapper.addAdminUser(admin);
        userMapper.distributeRole4User(admin.getUserId(), RoleType.NORMAL_ADMIN.getCode());
        if (add){
            admin.setPassword(pw);
        }
        return admin;
    }

    @Override
    public AdminUser adminLogin(AdminUser admin) {
        AdminUser adminInfo = adminMapper.getAdminCinemaId(admin.getUserId());
        String pw = admin.getPassword();
        Digester digester = DigestUtil.digester("sm3");
        String digesterPw = digester.digestHex(pw);

        if (adminInfo.getPassword().equals(digesterPw)){
            return adminInfo;
        }else {
            throw new GlobalException(Status.LOGIN_ERROR);
        }



    }
}
